# coding=utf8
import json
import time

from libs.dbs import MongoBase
from libs.dbs import model_redis
from libs.help import get_num_str
from libs.sele import driver_new_session

LIST_KEY = 'DrugItem'
MORE_LIST_KEY = 'DrugItemMore'

model_drug_item = MongoBase('amazonDrugItem')
model_drug_item_viewed = MongoBase('amazonDrugItemViewed')


def get_list():
    driver.execute_script('document.body.scrollTop = document.body.scrollHeight')
    time.sleep(1)
    lis = driver.find_elements_by_css_selector('#s-results-list-atf li')
    for li in lis:
        try:
            link = li.find_element_by_css_selector('.a-spacing-top-mini a').get_attribute('href')
        except:
            continue
        model_redis.lpush(LIST_KEY, link)
    driver.execute_script('document.body.scrollTop = document.body.scrollHeight')


def get_bought_asin():
    try:
        items_json = json.loads(driver.find_element_by_css_selector('#purchase-sims-feature > div').get_attribute(
            'data-a-carousel-options'))
        return items_json['baseAsin'], items_json['ajax']['id_list']
    except:
        print("没有购买过相关物品1")

    try:
        items_json = json.loads(driver.find_element_by_css_selector('#day0-sims-feature > div').get_attribute(
            'data-a-carousel-options'))
        return items_json['baseAsin'], items_json['ajax']['id_list']
    except:
        print("没有购买过相关物品2")

    import re
    asin_pattern = re.compile(r'B[A-Z|0-9]{9}')
    asin = asin_pattern.search(driver.current_url)
    return asin, []


def clear_cart():
    while True:
        try:
            driver.find_element_by_css_selector('span.a-size-small.sc-action-delete').click()
        except:
            break
    print('清空购物车')


def save_item(url, check_more=True):
    print('统计商品')
    driver.get(url)
    # check option
    if check_more:
        print('获取more')
        try:
            twister = driver.find_element_by_css_selector('#twisterContainer')
            map(lambda more_item_url: model_redis.lpush(MORE_LIST_KEY, 'https://www.amazon.com' + more_item_url),
                [item.get_attribute('data-dp-url') for item in
                 twister.find_elements_by_css_selector('.twisterShelf_swatch')])
        except:
            pass

    # save viewed item
    base_asin, bought_asin = get_bought_asin()
    if bought_asin and not model_drug_item_viewed.find_one({'Asin': base_asin}):
        print('获取买过记录')
        model_drug_item_viewed.insert_one({
            'Asin': base_asin,
            # 'Viewed': get_viewed_asin(),
            'Bought': bought_asin
        })
        # map(lambda asin: model_redis.lpush(LIST_KEY, "https://www.amazon.com/gp/product/{asin}".format(asin=asin)),
        #    bought_asin)

    try:
        if model_drug_item.find_one({'ASIN': base_asin}):
            print("重复了")
            return False
        driver.find_element_by_css_selector('#add-to-cart-button').click()
        print('加入购物车')
    except:
        return False

    statics_cart(base_asin)


def get_stock_number(item):
    print("获取库存")
    item.find_element_by_css_selector(
        'div.a-column.a-span2.a-text-right.sc-action-links.a-span-last > div > div').click()
    time.sleep(2)
    driver.find_element_by_css_selector('#dropdown1_9').click()
    time.sleep(2)
    print('输入999')
    try:
        item.find_element_by_css_selector(
            'div.a-column.a-span2.a-text-right.sc-action-links.a-span-last > div > div > input').send_keys('999')
    except:
        print('fail to send 999 to input')
    time.sleep(1.5)
    item.find_element_by_css_selector('.sc-update-link').click()

    # get alert
    time.sleep(2)
    try:
        alert = driver.find_element_by_css_selector(
            '#activeCartViewForm > div.sc-list-body > div:nth-child(1) > div.sc-list-item-content >'
            ' div.sc-quantity-update-message.a-spacing-top-mini > div > div > div > span').get_attribute(
            'innerHTML')
        num = get_num_str(alert)
    except:
        num = '1000+'

    return num


def statics_cart(asin):
    print('开始统计购物车')
    driver.get('https://www.amazon.com/gp/cart/view.html/ref=nav_cart')

    items = driver.find_elements_by_css_selector('.sc-list-body div.sc-list-item')
    for item in items:
        title_link = item.find_element_by_css_selector('.a-list-item .sc-product-link')
        # title_href = title_link.get_attribute('href')
        title = title_link.find_element_by_css_selector('span').get_attribute('innerHTML').strip()

        # vendor = item.find_element_by_css_selector('.a-list-item > span').get_attribute(
        #    'innerHTML').replace('by ').strip()
        # print(vendor)
        price = item.find_element_by_css_selector('.sc-price').get_attribute('innerHTML')
        print(price)

        in_stock_num = get_stock_number(item)

        clear_cart()

        model_drug_item.insert_one({
            'Title': title,
            'Price': price,
            'StockNum': str(in_stock_num),
            # 'Vendor': vendor,
            'ASIN': asin,
            # 'Href': title_href
        })
        print("新增成功一个")


def get_item_to_redis(next_url):
    driver.get(next_url)
    while True:
        get_list()
        try:
            pn = driver.find_element_by_css_selector('a#pagnNextLink')
            pn.click()
        except:
            print('no next page')
            break
        print('get next page')
        time.sleep(1)


def loop_items():
    last_id = None
    while True:
        res = model_drug_item_viewed.get_list(1000, last_id=last_id)
        if res.count(True) < 1:
            break
        for item in res:
            asin_s = list(set([item['Asin']] + item['Bought']))
            res_items = model_drug_item.find({'Asin': {
                '$in': asin_s
            }}, {'Asin': 1})
            map(asin_s.remove, [res_item['Asin'] for res_item in res_items])
            yield asin_s
            last_id = item['_id']


if __name__ == '__main__':
    for asin_s in loop_items():
        print(asin_s)
        for asin in asin_s:
            model_redis.lpush(LIST_KEY, "https://www.amazon.com/gp/product/{asin}".format(asin=asin))
    exit()
    driver = driver_new_session()
    # 登录
    driver.get(
        'https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fs'
        'pecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0'
        '%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.'
        'ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to='
        'https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_ya_signin')
    driver.find_element_by_id('ap_email').send_keys('ngl77924@163.com')
    driver.find_element_by_id('ap_password').send_keys('rwlm5244')
    driver.find_element_by_id('signInSubmit').click()

    while True:
        item_url = model_redis.rpop(LIST_KEY)
        if not item_url:
            break
        try:
            save_item(item_url)
        except:
            print(item_url)
            # 进入购物车清空下
            driver.get('https://www.amazon.com/gp/cart/view.html/ref=nav_cart')
            clear_cart()
            model_redis.lpush(LIST_KEY, item_url)
            continue
        time.sleep(1)

    # get more
    print("检查重复项")
    while True:
        item_url = model_redis.rpop(MORE_LIST_KEY)
        if not item_url:
            break
        try:
            save_item(item_url, False)
        except:
            print(item_url)
            # 进入购物车清空下
            driver.get('https://www.amazon.com/gp/cart/view.html/ref=nav_cart')
            clear_cart()
            model_redis.lpush(MORE_LIST_KEY, item_url)
            continue
        time.sleep(1)
